﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Net
{
    public class ByteArrayParser
    {
        /// <summary>
        /// 将可序列化对象转成的byte数组还原为对象
        /// </summary>
        /// <param name="b">byte数组</param>
        /// <returns>相关对象</returns>
        public static object ByteArrayToObject(byte[] b)
        {
            MemoryStream ms = new MemoryStream(b, 0, b.Length);
            BinaryFormatter bf = new BinaryFormatter();
            return bf.Deserialize(ms);
        }

        /// <summary>
        /// 将可序列化对象转成的byte数组还原为对象
        /// </summary>
        /// <param name="b">byte数组</param>
        /// <param name="offset">byte数组要开始转换的编移量</param>
        /// <param name="length">转换数组的长度</param>
        /// <returns></returns>
        public static object ByteArrayToObject(byte[] b, int offset, int length)
        {
            MemoryStream ms = new MemoryStream(b, offset, length);
            BinaryFormatter bf = new BinaryFormatter();
            return bf.Deserialize(ms);
        }

        /// <summary>
        /// 将可序列化对象转成Byte数组
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>返回相关数组</returns>
        public static byte[] ObjectToByteArray(object o)
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, o);
            ms.Close();
            return ms.ToArray();
        }
    }
}
